package com.streaminggbs.controller;

import com.github.pagehelper.PageInfo;
import com.streaminggbs.common.base.BaseQueryBean;
import com.streaminggbs.common.base.ErrorCodeException;
import com.streaminggbs.common.base.ReturnBean;
import com.streaminggbs.common.config.StaticConfig;
import com.streaminggbs.entity.DeviceInfo;
import com.streaminggbs.entity.LoginUser;
import com.streaminggbs.entity.SysAuthDept;
import com.streaminggbs.interfaces.DeviceInfoService;
import com.streaminggbs.interfaces.SysAuthDeptService;
import com.streaminggbs.common.utils.DateUtil;
import com.streaminggbs.common.utils.IDManager;
import com.streaminggbs.common.utils.RedisUtil;
import com.streaminggbs.common.utils.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

/**
 * @Author LiLin
 * @Date 2020/9/11 9:23
 * @Description 设备管理
 */
@Api(tags = {"设备管理接口"})
@Slf4j
@RestController
@RequestMapping("deviceInfo")
public class DeviceInfoController {

    @Autowired
    private DeviceInfoService deviceInfoService;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private SysAuthDeptService sysAuthDeptService;

    @ApiOperation(value = "获取设备信息列表", notes = "获取设备信息列表")
    @RequestMapping(value = "list", method = RequestMethod.GET)
    public ResponseEntity<ReturnBean> list(
            @ApiParam(value = "分页参数，从1开始") @RequestParam(value = "page", required = false/*, defaultValue = "1"*/) Integer page,
            @ApiParam(value = "分页用") @RequestParam(value = "limit", required = false/*, defaultValue = "10"*/) Integer limit,
            BaseQueryBean baseQueryBean,
            @ModelAttribute LoginUser loginUser) {
        if (loginUser == null) {
            return new ResponseEntity<>(new ReturnBean(new PageInfo()), HttpStatus.OK);
        }
        if ("0".equals(baseQueryBean.getDeptid()) ) {
            baseQueryBean.setDeptid(null);
        }
        PageInfo<DeviceInfo> list = new PageInfo<>();
        try {
            baseQueryBean.setBelongDeptid(loginUser.getSysUser().getDeptid());
            if(baseQueryBean.getDeptid()!=null) {
                SysAuthDept sysAuthDept = sysAuthDeptService.selectByKey(baseQueryBean.getDeptid());
                if(sysAuthDept!=null) {
                    baseQueryBean.setDeptidnew(sysAuthDept.getDeptidnew());
                }
            }
            if(page==null ||limit==null) {
                list = deviceInfoService.selectAllList(baseQueryBean);
            }else{
                list = deviceInfoService.selectPageList(baseQueryBean, page, limit);
            }
        } catch (Exception e) {
            log.error("获取当前的设备信息异常!{}", e);
        }
        return new ResponseEntity<>(new ReturnBean(list), HttpStatus.OK);
    }

    @ApiOperation(value = "添加设备", notes = "添加设备")
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public ReturnBean add(
            @ApiParam(value = "机构ID") @RequestParam(value = "deptid", required = true, defaultValue = "1") String deptid,
            @ApiParam(value = "设备编号") @RequestParam(value = "device", required = true) String device,
            @ApiParam(value = "设备名") @RequestParam(value = "devicename", required = true) String devicename,
            @ApiParam(value = "通道个数") @RequestParam(value = "channels", required = true) Integer channels,
            @ApiParam(value = "设备类型ID") @RequestParam(value = "devicetypeid", required = true) String devicetypeid,
            @ApiParam(value = "IP地址") @RequestParam(value = "ip", required = false) String ip,
            @ApiParam(value = "端口") @RequestParam(value = "port", required = false) String port,
            @ApiParam(value = "接入密码") @RequestParam(value = "password", required = false) String password,
            @ApiParam(value = "安装时间") @RequestParam(value = "installTimeStr", required = false) String installTimeStr,
            @ApiParam(value = "安装位置") @RequestParam(value = "location", required = false) String location,
            DeviceInfo entity
    ) {
        log.info("======添加设备======>deptid:" + deptid + "，device:" + device + "，devicename:" + devicename
                + "，channels:" + channels + "，devicetypeid:" + devicetypeid + "，ip:" + ip + "，port:" + port
                + "，password:" + password + "，installTimeStr:" + installTimeStr + "，location:" + location);
        try {
            if (!StringUtil.isEmpty(installTimeStr)) {
                entity.setInstallTime(DateUtil.parse(installTimeStr, DateUtil.PATTERN_CLASSICAL_SIMPLE));
            }

            int count = deviceInfoService.addDeviceInfo(entity);

            if (count == -1) {
                return new ReturnBean(-1, "设备编码已存在");
            }

            return new ReturnBean("保存成功");
        } catch (Exception e) {
            log.error("==设备管理==添加设备报错==", e);
            throw new ErrorCodeException(StaticConfig.SYSTEM_ERROR);
        }
    }

    @ApiOperation(value = "编辑设备", notes = "编辑设备")
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public ReturnBean edit(
            @ApiParam(value = "设备ID") @RequestParam(value = "id", required = true) String id,
            @ApiParam(value = "机构ID") @RequestParam(value = "deptid", required = true) String deptid,
            @ApiParam(value = "设备编号") @RequestParam(value = "device", required = true) String device,
            @ApiParam(value = "设备名") @RequestParam(value = "devicename", required = true) String devicename,
            @ApiParam(value = "通道个数") @RequestParam(value = "channels", required = true) Integer channels,
            @ApiParam(value = "设备类型ID") @RequestParam(value = "devicetypeid", required = true) String devicetypeid,
            @ApiParam(value = "IP地址") @RequestParam(value = "ip", required = false) String ip,
            @ApiParam(value = "端口") @RequestParam(value = "port", required = false) String port,
            @ApiParam(value = "接入密码") @RequestParam(value = "password", required = false) String password,
            @ApiParam(value = "安装时间") @RequestParam(value = "installTimeStr", required = false) String installTimeStr,
            @ApiParam(value = "安装位置") @RequestParam(value = "location", required = false) String location,
            DeviceInfo entity
    ) {
        log.info("======编辑设备======>id:" + id
                + "，deptid:" + deptid + "，device:" + device + "，devicename:" + devicename
                + "，channels:" + channels + "，devicetypeid:" + devicetypeid + "，ip:" + ip + "，port:" + port
                + "，password:" + password + "，installTimeStr:" + installTimeStr + "，location:" + location);
        try {
            if (!StringUtil.isEmpty(installTimeStr)) {
                entity.setInstallTime(DateUtil.parse(installTimeStr, DateUtil.PATTERN_CLASSICAL_SIMPLE));
            }
            entity.setModifyDate(DateUtil.getDate());

            int count = deviceInfoService.editDeviceInfo(entity);

            if (count == -1) {
                return new ReturnBean(-1, "设备编码已存在");
            }

            return new ReturnBean("保存成功");
        } catch (Exception e) {
            log.error("==设备管理==编辑设备报错==", e);
            throw new ErrorCodeException(StaticConfig.SYSTEM_ERROR);
        }
    }

    @ApiOperation(value = "删除设备", notes = "删除设备")
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public ReturnBean delete(
            @ApiParam(value = "设备ID") @RequestParam(value = "id", required = true) String id
    ) {
        log.info("======删除设备======>id:" + id);
        try {
            DeviceInfo deviceInfo = deviceInfoService.selectByKey(id);

            deviceInfoService.deleteDeviceInfo(id,deviceInfo.getDevice());

            return new ReturnBean("保存成功");
        } catch (Exception e) {
            log.error("==设备管理==删除设备报错==", e);
            throw new ErrorCodeException(StaticConfig.SYSTEM_ERROR);
        }
    }

    @ApiOperation(value = "设备详情", notes = "设备详情")
    @RequestMapping(value = "/details", method = RequestMethod.GET)
    public ReturnBean details(
            @ApiParam(value = "设备ID") @RequestParam(value = "id", required = true) String id
    ) {
        log.info("======设备详情======>id:" + id);
        try {
            return new ReturnBean(deviceInfoService.selectByKey(id));
        } catch (Exception e) {
            log.error("==设备管理==设备详情报错==", e);
            throw new ErrorCodeException(StaticConfig.SYSTEM_ERROR);
        }
    }

    @ApiOperation(value = "批量生成设备信息", notes = "添加设备")
    @RequestMapping(value = "/batchGenerate", method = RequestMethod.POST)
    public ReturnBean batchGenerate(
            @ApiParam(value = "部门ID") @RequestParam(value = "deptId", required = true) String deptId,
            @ApiParam(value = "设备最小开始值编码") @RequestParam(value = "minDeviceNo", required = true) String minDeviceNo,
            @ApiParam(value = "通道最小开始值编码") @RequestParam(value = "minDeviceChannelNo", required = true) String minDeviceChannelNo,
            @ApiParam(value = "设备类型ID") @RequestParam(value = "devicetypeid", required = true) String devicetypeid,
            @ApiParam(value = "IP地址") @RequestParam(value = "ip", required = false) String ip,
            @ApiParam(value = "端口") @RequestParam(value = "port", required = false) String port,
            @ApiParam(value = "接入密码") @RequestParam(value = "password", required = false) String password,
            @ApiParam(value = "生成条数") @RequestParam(value = "generateNumber", required = true) Integer generateNumber) {
        try {
            if (minDeviceNo.length() <= 6 || minDeviceChannelNo.length() <= 6) {
                return new ReturnBean(-1, "生成的编码至少为6位开始");
            }
            Integer minDeviceNoNum = Integer.valueOf(minDeviceNo.substring(minDeviceNo.length()-6,minDeviceNo.length()));// 取六位循环
            Integer minDeviceChannelNoNum = Integer.valueOf(minDeviceChannelNo.substring(minDeviceChannelNo.length()-6,minDeviceChannelNo.length()));// 取六位循环
            for (int i = 0;i<= generateNumber;i++) {
                // 生成
                String noStr = String.format("%014d", Long.valueOf(minDeviceNo.substring(0,minDeviceNo.length()-6)))+String.format("%06d", minDeviceNoNum+i);
                DeviceInfo deviceInfo = new DeviceInfo();
                deviceInfo.setId(IDManager.nextId());
                deviceInfo.setDeptid(deptId);
                deviceInfo.setDevicetypeid(devicetypeid);
                deviceInfo.setPassword(password);
                deviceInfo.setDevicename("自动生成设备"+noStr);
                deviceInfo.setCreateDate(new Date());
                deviceInfo.setDevice(noStr);
                deviceInfo.setIp(ip);
                deviceInfo.setPort(port);
                int count = deviceInfoService.addDeviceInfoAndChannel(deviceInfo,String.format("%014d", Long.valueOf(minDeviceChannelNo.substring(0,minDeviceNo.length()-6)))+String.format("%06d", minDeviceChannelNoNum+i));
                if (count == -1) {
                    return new ReturnBean(-1, "设备编码已存在");
                }
            }
            return new ReturnBean("保存成功");
        } catch (Exception e) {
            log.error("==设备管理==添加设备报错==", e);
            throw new ErrorCodeException(StaticConfig.SYSTEM_ERROR);
        }
    }
}
